<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Keep Account</title>
        <link rel="stylesheet" type="text/css" href="/res/common.css" /> 
        <style>
            .one_input_layout { width: 320px; height: 25px; float: left;}
            .one_line_layout { width: 720px; height: 25px; padding: 3px 0px 3px 0px;}
            .input_line_element { 
                float: left;
                width: 128px; 
                height: 20px;
                margin-top: 8px;
                margin-bottom: 8px;
            }
            #main_data {
                margin-top: 28px;
            }
        </style>
        <script type="text/javascript" src="/res/common.js"></script>
        <script type="text/javascript" src="/res/SimpleTable.js"></script>
    </head>
    <body>
        <div id="navi_bar">
        </div>
        <div id="data_show">
            <div class="one_line_layout">
                <div class="one_input_layout" >
                    <p class="input_line_element" >Type:</p>
                    <select class="input_line_element" id="record_type_select" onchange="onRecordTypeChange()">
                        <option value='income'>Income</option>
                        <option value='payment'>Payment</option>
                        <option value='transfer'>Transfer</option>
                    </select>
                </div>
            </div>
            <div class="one_line_layout">
                <div class="one_input_layout" >
                    <p class="input_line_element" >Currency:</p>
                    <select class="input_line_element" id="currency_select" onchange="onCurrencySelectChange()">
                        <option value="null">All</option>
                        <!-- <option class="currency_select_opt" value="0">Plase select</option> -->
                    </select>
                </div>
                <div class="one_input_layout" >
                    <p class="input_line_element" >Account:</p>
                    <select class="input_line_element" id="account_select">
                        <option value="null">All</option>
                    </select>
                </div>
            </div>
            <div class="one_line_layout">
                <div class="one_input_layout" >
                    <p class="input_line_element">Begin time:</p>
                    <textarea class="input_line_element" id="begin_time_input" ></textarea>
                </div>
                <div class="one_input_layout" >
                    <p class="input_line_element">End time:</p>
                    <textarea class="input_line_element" id="end_time_input" ></textarea>
                </div>
            </div>
            <div id="quick_buttons">
            </div>
            <div class="one_line_layout">
                <div class="one_input_layout" >
                    <p class="input_line_element" >Src Account:</p>
                    <select class="input_line_element" id="src_account_select" disabled="true">
                        <option value="null">All</option>
                    </select>
                </div>
                <div class="one_input_layout" >
                    <p class="input_line_element" >Dst Account:</p>
                    <select class="input_line_element" id="dst_account_select" disabled="true">
                        <option value="null">All</option>
                    </select>
                </div>
            </div>
            <div class="one_line_layout">
                <div class="one_input_layout" >
                    <p class="input_line_element" >Cat1:</p>
                    <select class="input_line_element" id="cat1_select" onchange="onCat1SelectChange()">
                        <!-- <option class="cat1_select_opt" value="0">Plase select</option> -->
                        <option value="null">All</option>
                    </select>
                </div>
                <div class="one_input_layout" >
                    <p class="input_line_element" >Cat2:</p>
                    <select class="input_line_element" id="cat2_select" disabled="true">
                        <!-- <option class="cat2_select_opt" value="0">Plase select</option> -->
                        <option value="null">All</option>
                    </select>
                </div>
            </div>
            <div class="one_line_layout">
                <div class="one_input_layout" >
                    <p class="input_line_element" >Description:</p>
                    <textarea class="input_line_element" id="description_val"></textarea>
                </div>
                <div class="one_input_layout" >
                    <p class="input_line_element" >User:</p>
                    <select class="input_line_element" id="user_select">
                        <!-- <option class="user_select_opt" value="0">Plase select</option> -->
                        <option value="null">All</option>
                    </select>
                </div>
            </div>
            <button id="okay_button" onclick="onOkayClick()">Okay</button>
        </div>
        <div id="main_data">

        </div>
    </body>
    <script>
        accountList = [];
        var income_cat = [];
        var payment_cat = [];
        var transfer_cat = [];
        var payment_cat1_cat2 = {};
        var g_record_type; var begin_time_input; var end_time_input; var g_account_id;
        var g_src_account_id; var g_dst_account_id; var g_cat1_id;
        var g_cat2_id; var g_amount; var g_description;
        
        function genOperationContent(id, record_type) {
            return '<a style="padding:0px 10px 0px 10px;" href="" onclick="del_rcd(' + id + ',\'' + record_type + '\');return false;">Delete</a>'
                +  '<a style="padding:0px 10px 0px 10px;" href="" onclick="edit_rcd(' + id + ',\'' + record_type + '\');return false;">Edit</a>';
        }

        function onRecordsReturn(result) {
            // 解析返回數據內容
            // 生成表格并顯示
            var result = JSON.parse(result);
            if(result.errno != 0) {
                alert('errno:' + result.errno + ' message:' + result.message);
            }
            var record_type = document.getElementById('record_type_select').value;
            var table_headers = {
                income: ['Record ID', 'User', 'Time', 'Account Name', 'Cat1 Name', 'Amount', 'Description', 'Operate'],
                payment: ['Record ID', 'User', 'Time', 'Account Name', 'Cat1 Name', 'Cat2 Name', 'Amount', 'Description', 'Operate'],
                transfer: ['Record ID', 'User', 'Time', 'SRC Account Name', 'DST Account Name', 'Cat1 Name', 'Amount', 'Description', 'Operate']};
            var table_header = table_headers[record_type];
            var operationContent;
            var table = new SimpleTable('data_table', 'main_data');
            var total_cost_row = [{'colspan':1, 'rowspan':1, 'text':'Total Cost: ' + result.data.total_cost}]; // 后面根据不同情况修改colspan的值
            table.setHeader(table_header);
            if(record_type == 'income') {
                result.data.records.forEach(function(row) {
                    operationContent = genOperationContent(row.rcd_id, record_type);
                    var row_data = [row.rcd_id, row.user_name, row.timeme, row.acnt_name, row.cat1_name, row.amount, row.describebe, operationContent];
                    table.addRow(row_data);
                });
                total_cost_row[0].colspan = table_headers.income.length;
                table.addRow(total_cost_row);
            }
            else if (record_type == 'payment') {
                result.data.records.forEach(function(row) {
                    operationContent = genOperationContent(row.rcd_id, record_type);
                    var row_data = [row.rcd_id, row.user_name, row.timeme, row.acnt_name, row.cat1_name, row.cat2_name, row.amount, row.describebe, operationContent];
                    table.addRow(row_data);
                });
                total_cost_row[0].colspan = table_headers.payment.length;
                table.addRow(total_cost_row);
            }
            else if (record_type == 'transfer') {
                result.data.records.forEach(function(row) {
                    operationContent = genOperationContent(row.rcd_id, record_type);
                    var row_data = [row.rcd_id, row.user_name, row.timeme, row.src_acnt_name, row.dst_acnt_name, row.cat1_name, row.amount, row.describebe, operationContent];
                    table.addRow(row_data);
                });
                total_cost_row[0].colspan = table_headers.transfer.length;
                table.addRow(total_cost_row);
            }
            table.show();
            document.getElementById('okay_button').disabled = false;
        }

        function onOkayClick() {
            // 清空舊表格
            var main_data = document.getElementById('main_data');
            var table = document.getElementById('data_table');
            if(table != null) {
                main_data.removeChild(table);
            }
            // 獲取所有輸入內容
            g_record_type = encodeURIComponent(document.getElementById('record_type_select').value);
            g_begin_time = encodeURIComponent(document.getElementById('begin_time_input').value);
            g_end_time = encodeURIComponent(document.getElementById('end_time_input').value);
            g_account_id = encodeURIComponent(document.getElementById('account_select').value);
            g_src_account_id = encodeURIComponent(document.getElementById('src_account_select').value);
            g_dst_account_id = encodeURIComponent(document.getElementById('dst_account_select').value);
            g_cat1_id = encodeURIComponent(document.getElementById('cat1_select').value);
            g_cat2_id = encodeURIComponent(document.getElementById('cat2_select').value);
            g_description = encodeURIComponent(document.getElementById('description_val').value);
            g_user_id = encodeURIComponent(document.getElementById('user_select').value);
            // 拼URL
            uri = '';
            if(g_account_id != 'null')  { uri += '&account_id=' + g_account_id; }
            if(g_user_id != 'null')     { uri += '&user_id=' + g_user_id; }
            if(g_begin_time != '')      { uri += '&begin_time=' + g_begin_time; }
            if(g_end_time != '')        { uri += '&end_time=' + g_end_time; }
            if(g_cat1_id != 'null')     { uri += '&cat1_id=' + g_cat1_id; }
            if(g_cat2_id != 'null')     { uri += '&cat2_id=' + g_cat2_id; }
            if(uri != '')               { uri = '?' + uri.substr(1); }
            if(g_record_type == 'income')           { uri = '/service/record/getIncome' + uri; }
            else if(g_record_type == 'payment')     { uri = '/service/record/getPayment' + uri; }
            else if(g_record_type == 'transfer')    { uri = '/service/record/getTransfer' + uri; }
            document.getElementById('okay_button').disabled = true;
            getUrlAsyn(uri, onRecordsReturn);
        }

        function resetCat1Select(cat1_list) {
            // 先刪除select下的所有選項
            cat1_select = document.getElementById('cat1_select');
            clearSubElement(cat1_select, 'cat1_select_opt');
            // 再向select添加新的選項
            cat1_list.forEach(function(ele) {
                appendSelectorOption(cat1_select, ele.cat1_id, ele.nameme, 'cat1_select_opt');
            });
        }

        function setPaymentCat1And2() {
            resetCat1Select(payment_cat);
            cat2_select = document.getElementById('cat2_select');
            clearSubElement(cat2_select, 'cat2_select_opt');
            selected_cat1_id = document.getElementById('cat1_select').selectedOptions.item(0).value
            if(selected_cat1_id == "null") {
                return;
            }
            cat2_list = payment_cat[selected_cat1_id].cat2_list;
            cat2_list.forEach(function(ele) {
                appendSelectorOption(cat2_select, ele.cat2_id, ele.nameme, 'cat2_select_opt');
            })
        }

        function onRecordTypeChange() {
            var select = document.getElementById('record_type_select');
            switch(select.value) {
                case 'income':
                    cat2_select = document.getElementById('cat2_select')
                    cat2_select.disabled = true;
                    document.getElementById('account_select').disabled = false;
                    document.getElementById('src_account_select').disabled = true;
                    document.getElementById('dst_account_select').disabled = true;
                    document.getElementById('cat2_select').selectedIndex = 0;
                    resetCat1Select(income_cat);
                    clearSubElement(cat2_select, 'cat2_select_opt');
                    break;
                case 'payment':
                    document.getElementById('cat2_select').disabled = false;
                    document.getElementById('account_select').disabled = false;
                    document.getElementById('src_account_select').disabled = true;
                    document.getElementById('dst_account_select').disabled = true;
                    setPaymentCat1And2();
                    break;
                case 'transfer':
                    cat2_select = document.getElementById('cat2_select')
                    cat2_select.disabled = true;
                    document.getElementById('account_select').disabled = true;
                    document.getElementById('src_account_select').disabled = false;
                    document.getElementById('dst_account_select').disabled = false;
                    document.getElementById('cat2_select').selectedIndex = 0;
                    resetCat1Select(transfer_cat);
                    clearSubElement(cat2_select, 'cat2_select_opt');
                    break;
                default: break;
            }
        }

        function onCurrencySelectChange() {
            var crc_id = document.getElementById('currency_select').value;
            resetAccountListByCurrencyId(crc_id, currency_account);
        }

        function onCat1SelectChange() {
            // 只有在填寫payment的時候才處理
            if(document.getElementById('record_type_select').value != 'payment') {
                return;
            }
            cat2_select = document.getElementById('cat2_select');
            clearSubElement(cat2_select, 'cat2_select_opt');
            selected_cat1_id = document.getElementById('cat1_select').value;
            if(selected_cat1_id == "null") {
                return;
            }
            cat2_list = payment_cat1_cat2[selected_cat1_id];
            cat2_list.forEach(function(cat2_item) {
               appendSelectorOption(cat2_select, cat2_item.cat2_id, cat2_item.nameme, 'cat2_select_opt') ;
            });
        }

        function onUIContentReceived(result) {
            result = JSON.parse(result);

            // 一、处理account相关的内容
            var opt = {};
            currency_account = result.data.account.data;
            // 生成币种菜单
            for(var crc_id in currency_account) {
                currency_info = currency_account[crc_id]
                opt = document.createElement('option');
                opt.value = currency_info.crc_id;
                opt.text = currency_info.nameme;
                document.getElementById('currency_select').appendChild(opt);
            }
            // 用第一个crc_id生成账户菜单
            resetAccountListByCurrencyId(Object.keys(currency_account)[0], currency_account);
            
            // 二、处理三种cat
            income_cat = result.data.income_cat.data;
            transfer_cat = result.data.transfer_cat.data;
            payment_cat = result.data.payment_cat.data;  // 全局变量
            payment_cat.forEach(function(item) {
                cat1_id = item.cat1_id;
                payment_cat1_cat2[cat1_id] = item.cat2_list;
            });
            setPaymentCat1And2();
            
            // 三、处理users
            user_select = document.getElementById('user_select')
            result.data.users.data.forEach(function(item) {
                appendSelectorOption(user_select, item.user_id, item.nameme, 'user_select_opt');
            });

            // 默认展示的记录类型设为payment
            document.getElementById('record_type_select').value = 'payment';
            onRecordTypeChange();
        }

        function onRecordDeleted(result) {
            // TODO 解凍界面

            result = JSON.parse(result);
            if(result.errno == 0) {
                alert('successed~');
            }
            else {
                alert('errno:' + result.errno + ' message:' + result.message);
                return;
            }
            // 刷新結果
            onOkayClick();
        }

        function del_rcd(rcd_id, record_type) {
            // TODO 凍結界面
            var ret = confirm('Are you sure to delete this reocrd?');
            if(ret == false) {
                return;
            }
            if(record_type == 'payment') {
                getUrlAsyn('/service/record/deletePayment?rcd_id=' + rcd_id, onRecordDeleted);
            }
            else if(record_type == 'income') {
                getUrlAsyn('/service/record/deleteIncome?rcd_id=' + rcd_id, onRecordDeleted);
            }
            else if(record_type == 'transfer') {
                getUrlAsyn('/service/record/deleteTransfer?rcd_id=' + rcd_id, onRecordDeleted);
            }
        }

        function edit_rcd(rcd_id, record_type) {

        }

        genNavBar('records');
        genTimeRangeQuickButton('quick_buttons', 'begin_time_input', 'end_time_input');
        getUrlAsyn('/service/ui/records', onUIContentReceived);
        document.getElementById('end_time_input').innerHTML = getCurrentDateTimeString(0, true);
        document.getElementById('begin_time_input').innerHTML = getCurrentDateTimeString(-1000 * (24 * 60 * 60 * 30), true); // 一月前
    </script>
</html>
